Skip to content

Fix deleted external events during a continue-as-new - #1399

Merged
sophiatev merged 9 commits into
mainfrom
stevosyan/fix-dropped-external-events
Sep 11, 2026
Merged

sophiatev merged 9 commits into
mainfrom
stevosyan/fix-dropped-external-events

Conversation

@sophiatev

@sophiatev sophiatev commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

We currently have a bug which deletes external events for a continue-as-new. Consider the following sequence:

  1. An orchestration continues-as-new, and schedules a task. The task completes with a TaskCompleted event sent to the new execution ID of the orchestration, before the new history of the orchestration has been committed. In combination, an EventRaised is sent to the orchestration (with no target execution ID).
  2. These messages both end up in the same message batch in the OrchestrationSessionManager. Since the TaskCompleted message has an execution ID, this becomes the execution ID of the message batch.
  3. When performing the orchestration history fetch to process the message batch, no history is found because the history for the new execution ID has not been committed.
  4. When attempting to generated the next work item, IsOutOfOrder correctly deems the TaskCompleted event as out of order since it has no matching TaskScheduled in the empty history. This message is correctly abandoned and retried. The EventRaised should also be retried, but the problem occurs at this line - since the EventRaised does not match the execution ID of the orchestration session, it is first correctly added to the abandon list. However, because there end up being no messages to delete, our current logic decides that all of the messages must have been external events with no target execution ID, and it must be the case that the orchestration has completed or been purged. It neglects to take into account the situation where an orchestration continues-as-new, which is why no history was returned for the session's execution ID. This PR simply updates the logic to take this scenario into account by only allowing a full delete of messages if the session's execution ID is null. This means that there cannot be a race condition involving different execution IDs. The most recently stored execution ID would have been prefetched, and so it is indeed safe to say that either there is no history or the orchestration has completed.

Copilot AI lite review requested due to automatic review settings September 9, 2026 20:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new test asserts an exact queue “approximate” message count, which is prone to flakiness and should be made more robust to avoid intermittent CI failures.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR fixes a race-condition bug in the Azure Storage backend where execution-independent external events (no target execution ID) could be incorrectly deleted when batched with an out-of-order message for a not-yet-committed ContinueAsNew execution.

Changes:

  • Update discard logic to only “delete all messages in batch” when the session execution ID is null (eliminating the ContinueAsNew false-positive).
  • Avoid building/logging a discard event list when there are no messages actually being discarded.
  • Add a regression scenario test to ensure execution-independent events aren’t lost when batched with an out-of-order message for a missing execution.
File summaries
File Description
test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs Adds a regression test covering mixed batches (missing execution + execution-independent external event).
src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs Tightens the “discard all” condition to prevent deleting retriable external events during ContinueAsNew races; guards discard logging.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Copilot AI review requested due to automatic review settings September 10, 2026 18:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The logic change is narrowly scoped, aligns with the PR’s stated race scenario, and is backed by a targeted regression test (only minor comment-grammar nits noted).

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs:836

  • Comment punctuation/grammar: the final sentence is missing a period, and the phrasing can be tightened for clarity (especially around ContinueAsNew).
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 18:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new test asserts an exact value from an API that is explicitly approximate, which can introduce avoidable CI flakiness.

Review details

Suppressed comments (2)

Previously missed (1) — in code that hasn't changed since the last review.

src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs:850

  • When building the discarded-event list for logging, the StringBuilder capacity is based on orchestrationWorkItem.NewMessages.Count even though only messagesToDiscard are appended. Using messagesToDiscard.Count keeps the capacity estimate aligned with the actual loop and avoids over-allocation when only a subset is discarded.

test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs:4055

  • The test asserts an exact value from GetApproximateMessagesCountAsync(), but the underlying Azure Queue ApproximateMessagesCount is explicitly approximate and can be stale. This can make the test flaky even when the behavior is correct; the later assertion that the retried work item contains both TimerFiredEvent and EventRaisedEvent already verifies the key requirement (that neither message was deleted).
                Assert.AreEqual(
                    2,
                    await controlQueue.InnerQueue.GetApproximateMessagesCountAsync(),
                    "The out-of-order timer and execution-independent event should both remain on the queue.");
  • Files reviewed: 2/2 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 22:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Use the runtime state's empty-history check to avoid deleting deferred events for legacy null-execution histories.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Preserve execution-independent events until newer execution state is verified.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 10, 2026 23:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical event-deferral issue remains, and the new queue-count assertions are unreliable.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (2)

src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs:837

  • When this batch is anchored to a stale execution, this override deletes messages for other executions too. A ContinueAsNew history is marked ContinuedAsNew and therefore isKnownTerminalInstance, so if an old TaskCompleted/TimerFired and a null-target EventRaised are batched before the new execution is committed, the EventRaised is moved from messagesToAbandon into messagesToDiscard here and lost instead of being retried for the new generation. Only take the full-delete path after confirming that the terminal state is for the current/latest execution; otherwise retain messages whose target execution differs.
                        if (isKnownTerminalInstance)
                        {
                            messagesToDiscard.AddRange(messagesToAbandon);
                            messagesToAbandon.Clear();

test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs:663

  • AllControlQueues includes every partition in the task hub, not just the queue used by the test. In particular, WorkerAttemptingToDequeueMessageForNonExistentInstance uses the shared TestHelpers.GetTestTaskHubName() and default four partitions, so this helper can count unrelated messages on another partition and make the new exact-empty assertions fail. Use a unique task hub or assert only against the specific queue/message created by the test.
                service.AllControlQueues.Select(queue => queue.InnerQueue.GetApproximateMessagesCountAsync()));
  • Files reviewed: 2/2 changed files
  • Comments generated: 2
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 11, 2026 05:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical and moderate findings affect message preservation and test reliability.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (3)

src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs:842

  • On the continue-as-new retry, this predicate is no longer true: the out-of-order TaskCompleted was removed from CurrentMessageBatch, while the EventRaised was put in DeferredMessages; TryReleaseSession then re-adds it with its null execution ID. That creates a new null-ID batch, and before the new generation checkpoint GetHistoryEventsAsync(..., null) can read the old generation's ContinueAsNew history, causing IsExecutableInstanceAsync to report a terminal instance and this branch to delete the event. Keep the deferred event associated with the future execution/start batch (or wait for that history) instead of re-batching it as execution-independent, and cover a second dequeue before the new history is committed.
                        if (messagesToDiscard.Count == 0 && !matchingExecutionMessageWasAbandoned)
                        {
                            messagesToDiscard.AddRange(messagesToAbandon);
                            messagesToAbandon.Clear();
                        }

test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs:4261

  • This test leaves PartitionCount at the default of 4 and uses the shared GetTestTaskHubName() task hub, but this assertion sums AllControlQueues, including partitions that this worker did not process. An unrelated message in another partition can make the test fail even though the target message was deleted; the previous check correctly scoped the assertion to OwnedControlQueues.Single(). Keep this assertion scoped to the queue owned by the test (or set PartitionCount = 1).
                Assert.AreEqual(
                    0,
                    await GetControlQueueMessageCountAsync(service),
                    "The message for the nonexistent orchestration should be deleted rather than abandoned.");

test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs:664

  • GetApproximateMessagesCountAsync() is explicitly an approximate Azure Queue metric, so asserting exact values (especially 0 immediately after DeleteMessageAsync) can be stale and make these new scenarios flaky even when the messages were correctly deleted. Poll until the expected count is observed or verify the specific queue messages with a retryable exact observation instead of treating this metric as authoritative.
                service.AllControlQueues.Select(queue => queue.InnerQueue.GetApproximateMessagesCountAsync()));
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 11, 2026 05:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No unresolved blocking issues were identified.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@sophiatev
sophiatev merged commit 26029f4 into main Sep 11, 2026
48 checks passed
@sophiatev
sophiatev deleted the stevosyan/fix-dropped-external-events branch September 11, 2026 17:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants